package com.plian.system.controller.sys.user;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.plian.Tools.base.BaseController;
import com.plian.system.entity.sys.Config;
import com.plian.system.mapper.sys.ConfigMapper;
import com.plian.system.model.token.PassToken;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping(value = "/healthy")
@RequiredArgsConstructor
public class HealthyController extends BaseController {

    private final ConfigMapper configMapper;
    private final String OPEN = "open";
    private final String CLOSE = "close";
    private final String OK = "ok";
    private final String TRUE = "true";
    private final String FALSE = "false";
    private final String TASK_STATUS = "task_status";


    /**
     * 健康监测
     *
     * @return
     */
    @GetMapping("/ping")
    @PassToken
    public String ping() {
        return "pong";
    }


    /**
     * 获取定时任务状态
     *
     * @return
     */
    @GetMapping("/getTaskStatus")
    @PassToken
    @Transactional(rollbackFor = Exception.class)
    public String getTaskStatus(@RequestParam String key) {
        Config config = configMapper.selectOne(Wrappers.lambdaQuery(Config.class).eq(Config::getCode, "task_status"));
        if (config == null){
            config = new Config();
            config.setCode(TASK_STATUS);
            config.setValue(TRUE);
            configMapper.insert(config);
            return OK;
        }
        if (OPEN.equals(key)) {
            if (FALSE.equals(config.getValue())) {
                config.setValue(TRUE);
                configMapper.updateById(config);
            }
            return OK;
        } else if (CLOSE.equals(key)) {
            if (TRUE.equals(config.getValue())) {
                config.setValue(FALSE);
                configMapper.updateById(config);
            }
            return OK;
        }else {
            throw new IllegalArgumentException("无效的key");
        }
    }


}
